/**
 * Created by jaliu on 2015/2/13.
 */


var Community = mongoose.model('community');
var User = mongoose.model('user');
var UserAuthentication = mongoose.model('user_authentications');
var async = require('async');
var moment = require('moment');

/**
 * 查询全部小区
 */
exports.getAllCommunityService = function (callback) {
    Community.find(null).exec(function (err, results) {
        if (results != null) {
            callback(null, results);
        } else {
            var msg = {
                "message": 'No such community'
            }
            callback(msg, null);
        }
    });
};

exports.searchFrontendUserService = function (communityObjId, mobilePhone, nickName, isVUser, isTalent, startDate, endDate, startPage, pageSize, callback) {

    var mobilePhoneQueryCond = {mobilePhone: new RegExp(mobilePhone)};
    var nickNameQueryCond = {nickName: new RegExp(nickName)};
    var communityObjIdQueryCond = {community: communityObjId};


    if (mobilePhone == 'all') {
        mobilePhoneQueryCond = null;
    }
    ;
    if (nickName == 'all') {
        nickNameQueryCond = null;
    }
    ;

    var isVUserQueryCond = null;
    var isTalentQueryCond = null;
    var dateQueryCond = null;

    if (isVUser == 'all') {
        isVUserQueryCond = null;
    } else if (isVUser == '是') {
        isVUserQueryCond = {authenticationStatus: true};
    } else {
        isVUserQueryCond = {authenticationStatus: false};
    }

    if (isTalent == 'all') {
        isTalentQueryCond = null;
    } else if (isTalent == '是') {
        isTalentQueryCond = {userType: 'talent'};
    } else {
        isTalentQueryCond = {userType: {'$ne': 'talent'}};
    }

    dateQueryCond = {dateCreated: {'$gte': new Date(startDate), '$lte': new Date(endDate)}};

    async.series([
        function (callbackInner) {
            User.count({$and: [communityObjIdQueryCond, mobilePhoneQueryCond, nickNameQueryCond, isVUserQueryCond, isTalentQueryCond, dateQueryCond]}, callbackInner);
        },
        function (callbackInner) {
            User.find({$and: [communityObjIdQueryCond, mobilePhoneQueryCond, nickNameQueryCond, isVUserQueryCond, isTalentQueryCond, dateQueryCond]})
                .populate('community', 'communityName')
                .populate('domainOfExpertise', 'value')
                .populate('homeTown.city', 'name')
                .populate('userPortrait', 'value')
                .sort('-dateCreated').skip(startPage).limit(pageSize).exec(function (err, result) {
                    if (result != null) {
                        result.forEach(function (temp) {
                            if (temp._doc.birthDate != null)
                                temp._doc.birthDate = moment(temp._doc.birthDate).format('YYYY-MM-DD')
                        })
                    }
                    callbackInner(null, result)
                });
        }
    ], callback);
}

exports.setCancelVUserService = function (userObjId, communityObjId, input, callback) {
    if (input.authenticationStatus == true) {
        async.series([
            function (callbackInner) {
                User.update({_id: userObjId}, {'authenticationStatus': input.authenticationStatus}, callbackInner);
            },
            function (callbackInner) {

                tempObj = new UserAuthentication();
                tempObj.user = userObjId;
                tempObj.community = communityObjId;
                //tempObj.imageURL = '';
                tempObj.status = true;
                tempObj.isValid = true;
                tempObj.refusalReason = '';
                tempObj.save(callbackInner)
            },
            function (callbackInner) {
                User.findOne({_id: userObjId}, 'invitedBy', function (err, user) {
                    callbackInner(err, user.invitedBy);
                });
            }
        ], callback);
    }
    else {
        async.series([
            function (callbackInner) {
                User.update({_id: userObjId}, {'authenticationStatus': input.authenticationStatus}, callbackInner);
            },
            function (callbackInner) {
                UserAuthentication.findOneAndRemove({user: userObjId, community: communityObjId}, callbackInner);
            }
        ], callback);
    }
}

exports.putFrontendUserToBlacklistService = function (userObjId, frozenOrNot, reason, callback) {
    User.update({_id: userObjId}, {'frozenOrNot': frozenOrNot, 'frozenReason': reason}, callback);
}

exports.setCancelFrontendUserAsTalentService = function (userObjId, talentDesc, type, callback) {
    if (type == '1') {
        User.update({_id: userObjId}, {
            'authenticationStatus': true,
            'userType': 'talent',
            'speciality': talentDesc
        }, callback);
    } else {
        User.update({_id: userObjId}, {
            'authenticationStatus': true,
            'userType': 'normalAppUser',
            'speciality': ''
        }, callback);
    }
}

exports.getUserAuthenticationInfoService = function (communityObjId, callback) {
    UserAuthentication.find({community: communityObjId}).exec(callback);
};

exports.updateService = function (id, input, callback) {
    User.update({_id: id}, input, callback);
};


